package com.showcai.controller.base;

import com.showcai.controller.utils.WeChatTools;
import com.showcai.controller.utils.WeiXinUtils;
import com.showcai.def.Constant;
import com.showcai.module.User;
import com.showcai.module.UserRelation;
import com.showcai.module.UserThird;
import com.showcai.module.wechat.UserWechatInfo;
import com.showcai.myRunTime.MyRunTimeExcption;
import com.showcai.util.FixedData;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by Baggio on 2017-5-2.
 */
public class WeChatBaseController extends BaseController {

    /**
     * 获取客户端浏览器来源是否是微信浏览器
     * (此功能暂时未完善)
     *
     * @param request
     * @return
     */
    protected boolean getBrowserSource(HttpServletRequest request) {
        String userAgent = request.getHeader("user-agent").toLowerCase();
        if (userAgent.indexOf("micromessenger") > -1) {
            logger.info("微信浏览器======》》》");
            return true;
        }
        logger.info("不是微信浏览器======》》》");
        return false;
    }

    /**
     * 判断客户端是否是移动端
     *
     * @return
     */
    protected boolean getIsMobile() {
        String userAgent = request.getHeader("user-agent");
        String[] agent = {
                "Android"
                , "iPhone"
                , "iPod"
                , "iPad"
                , "Windows Phone"
                , "MQQBrowser"};

        boolean flag = false;
        if (
                !userAgent.contains("Windows NT")
                        || (userAgent.contains("Windows NT") && userAgent.contains("compatible; MSIE 9.0;"))) {

            // 排除 苹果桌面系统
            if (!userAgent.contains("Windows NT") && !userAgent.contains("Macintosh")) {
                for (String item : agent) {
                    if (userAgent.contains(item)) {
                        flag = true;
                        break;
                    }
                }
            }
        }
        return flag;
    }

    /**
     * 判断是否是苹果
     *
     * @return
     */
    protected boolean getIsIPhone() {
        String userAgent = request.getHeader("user-agent");
        logger.info("userAgent is====>>" + userAgent);
        logger.info(userAgent.indexOf("iPhone"));
        boolean flag = false;
        if (userAgent.indexOf("iPhone") > -1 || userAgent.indexOf("iPod") > -1 || userAgent.indexOf("iPad") > -1) {
            logger.info("is IOS");
            flag = true;
        }
        logger.info("flag is==============>>>>>>>" + flag);

        return flag;
    }


    /**
     * 微信授权
     */

    protected void oauth2() {
        if (!getBrowserSource(request)) {
            logger.info("不是微信浏览器，不能鉴权");
            return;
        }
        String openId = getOpenId();
        if (StringUtils.isNotBlank(openId)) {
            logger.info("已经鉴权，不用再次鉴权=====》》》》》》" + openId);
            return;
        }
        String code = request.getParameter("code");
        if (StringUtils.isNotBlank(code)) {
            //获取openId
            getOpenId(code, FixedData.ENTERPRISE_APP_ID);
            return;
        }


        HttpServletRequest httpRequest = (HttpServletRequest) request;

        String toUrl = "https://www.showcai.com" //+ request.getServerName() //服务器地址
               /* + ":"
                + request.getServerPort()           //端口号
                */
                + httpRequest.getContextPath()      //项目名称
                + httpRequest.getServletPath();      //请求页面或其他地址

        String queryStr = httpRequest.getQueryString();
        if (StringUtils.isNotBlank(queryStr)) {
            toUrl += "?" + queryStr; //参数
        }
        logger.info(" ===========================u==============================================>/n" + toUrl);
        String u = WeiXinUtils.oauth2(toUrl, WeiXinUtils.SNSAPI_BASE, FixedData.ENTERPRISE_APP_ID);
        logger.info(" ===========================u==============================================>/n" + u);
        try {
            response.sendRedirect(u);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void oauth2_() {
        String code = request.getParameter("code");
        logger.info("oauth2_===============>>>鉴权"+code);
        if (!getBrowserSource(request)) {
            logger.info("不是微信浏览器，不能鉴权");
            return;
        }
        String openId = getOpenId();
        if (StringUtils.isNotBlank(openId)) {
            logger.info("已经鉴权，不用再次鉴权=====》》》》》》" + openId);
            return;
        }

        logger.info("code is====>>>" + code);
        if (StringUtils.isNotBlank(code)) {
            //获取openId
            // getOpenId(code, FixedData.ENTERPRISE_APP_ID);
            UserWechatInfo userWechatInfo = WeChatTools.getopenId2(FixedData.ENTERPRISE_APP_ID, code);
            logger.info(userWechatInfo.toString());
         //   super.session.setAttribute(Constant.SESSION_KEY_WECHAT_USER_INFO, userWechatInfo);
            super.session.setAttribute(Constant.SESSION_OPEN_ID, userWechatInfo.getOpenid());
            super.session.setAttribute(Constant.SESSION_KEY_WECHAT_IMG, userWechatInfo.getHeadimgurl());
            return;
        }


        HttpServletRequest httpRequest = (HttpServletRequest) request;

        String toUrl = "https://www.showcai.com" //+ request.getServerName() //服务器地址
               /* + ":"
                + request.getServerPort()           //端口号
                */
                + httpRequest.getContextPath()      //项目名称
                + httpRequest.getServletPath();      //请求页面或其他地址

        String queryStr = httpRequest.getQueryString();
        if (StringUtils.isNotBlank(queryStr)) {
            toUrl += "?" + queryStr; //参数
        }
        logger.info(" ===========================u==============================================>/n" + toUrl);
        String u = WeiXinUtils.oauth2(toUrl, WeiXinUtils.SNSAPI_USERINFO, FixedData.ENTERPRISE_APP_ID);
        logger.info(" ===========================u==============================================>/n" + u);
        try {
            response.sendRedirect(u);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void getOpenId(String code, String appId) throws MyRunTimeExcption {
        if (StringUtils.isNotBlank(code)) {

            String openId = WeChatTools.getopenId(appId, code);
            if (StringUtils.isBlank(openId)) {

                throw new MyRunTimeExcption("微信鉴权失败");
            }

            logger.info("openId is==============>>>" + openId);
            logger.info("session is==============>>>" + session.getId());
            logger.info("写入session====================================>>>>>>>" + openId);
            super.session.setAttribute(Constant.SESSION_OPEN_ID, openId);
            // super.session.setAttribute(Constant.SESSION_KEY_WECHAT_USER_INFO, userWechatInfo);

        }
    }

    protected String getOpenId() {
        return (String) super.session.getAttribute(Constant.SESSION_OPEN_ID);
    }

    protected UserWechatInfo getUserWechatInfo() {
        return (UserWechatInfo) super.session.getAttribute(Constant.SESSION_KEY_WECHAT_USER_INFO);
    }

    protected void addWechatUser(String thirdId, User user, Byte type) {
        if (StringUtils.isBlank(thirdId)) {
            logger.info("thirdId is null");
            return;
        }
        UserThird userThird = new UserThird();
        userThird.setThirdId(thirdId);
        userThird.setType(type);
        userThird = userThirdService.selectUserThird(userThird);
        if (userThird == null) {
            userThird = new UserThird();
            userThird.setThirdId(thirdId);
            userThird.setType(type);
            userThird = userThirdService.modifyUserThird(userThird);
            UserRelation userRelation = new UserRelation();
            userRelation.setUserId(user.getTid());
            userRelation.setThirdId(userThird.getTid());
            userRelation.setStatus(UserRelation.STATUS_VALID);
            userThirdService.modifyUserRelation(userRelation);
        }


    }
}
